package com.xgkj.diyiketang.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xgkj.diyiketang.activity.data.CaiPinAdapter;
import com.xgkj.diyiketang.data.CaiPinInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.CaiPinListTask;
import com.xgkj.diyiketang.task.DishDeleteTask;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;
import com.xgkj.diyiketang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/3/22.
 */
public class CaiPinListActivity extends BaseActivity implements PullToRefreshListView.OnRefreshListener,PullToRefreshListView.OnLoadDataListener,View.OnClickListener {
    private Context mContext;
    private PullToRefreshListView mListView;
    private CaiPinAdapter mAdapter;
    private int cityTaskId = -1;
    private int currentPage = 1;
    private int size = 10;
    private TextView back;
    private String mTitle;
    private TextView titleTextView;
    private String businessId;
    private int from;
    private TextView sureText;
    private String caipin_select;
    private List<String> select_caipin_list = new ArrayList<String>();
    //菜品管理等等
    private LinearLayout footLayout;
    private Button createDishBtn;
    private int deleteTaskId = -1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.caipinlist);
        mContext=this;
        initView();
    }

    private void initView(){
        Intent intent = getIntent();
        mTitle = intent.getStringExtra("TITLE");
        businessId = intent.getStringExtra("BUSINESSID");
        from = intent.getIntExtra("FROM",1);
        caipin_select = intent.getStringExtra("SELECT_CAIPIN");
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleTextView = (TextView) findViewById(R.id.shangjia_name);
        sureText = (TextView) findViewById(R.id.sure_btn);
        footLayout = (LinearLayout) findViewById(R.id.foot_layout);
        createDishBtn = (Button) findViewById(R.id.create_new_caipin);
        createDishBtn.setOnClickListener(this);
        if (from == 1){
            //商家推荐菜查看大图
            titleTextView.setText(mTitle);
            mAdapter = new CaiPinAdapter(mContext,false);
            sureText.setVisibility(View.GONE);
            footLayout.setVisibility(View.GONE);
        }else if (from == 2){
            //推荐菜选择
            titleTextView.setText(R.string.choose_caipin);
            mAdapter = new CaiPinAdapter(mContext,true);
            sureText.setVisibility(View.VISIBLE);
            footLayout.setVisibility(View.VISIBLE);
            if (!ViewUtil.isNull(caipin_select)){
                String[] arr = caipin_select.split("\n");
                for (int a=0;a<arr.length;a++){
                    select_caipin_list.add(arr[a]);
                }
                mAdapter.setSelectCaipin(select_caipin_list);
            }
        }else if (from == 3){
            //推荐菜管理
            titleTextView.setText(R.string.recommend_dish);
            mAdapter = new CaiPinAdapter(mContext,false);
            sureText.setVisibility(View.GONE);
            footLayout.setVisibility(View.VISIBLE);
        }
        sureText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String>select = mAdapter.getSelectCaipin();
                String selectCaipin = "";
                for (int i=0;i<select.size();i++){
                    selectCaipin+=select.get(i);
                    if (i!=select.size()-1){
                        selectCaipin+="\n";
                    }
                }
                Intent intent1 = new Intent();
                intent1.putExtra("SELECTCAIPIN",selectCaipin);
                intent1.putExtra("SELECT_ALREADY","已选择"+select.size()+"道菜");
                setResult(RESULT_OK,intent1);
                mAdapter.clearCaipin();
                finish();
            }
        });
        mListView = (PullToRefreshListView)findViewById(R.id.caipin_list);
        mListView.init(mContext,true);
        mListView.setAdapter(mAdapter, true);
        if (from ==1) {
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (mListView.getHeaderViewsCount() > 0) {
                        position--;
                    }
                    if (position < 0 || position >= mAdapter.getCount()) return;
                    CaiPinInfo fdinfo = (CaiPinInfo) mAdapter.getItem(position);
                    String bigImage = fdinfo.getDishBigLogo();
                    ArrayList<String> adlist = new ArrayList<String>();
                    adlist.add(bigImage);
                    Intent intent = new Intent(mContext, ShowBigImageActivity.class);
                    intent.putExtra("photoList",adlist);
                    intent.putExtra("currentPosition", 0);
                    startActivity(intent);
                }
            });
        }else if (from ==3){
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (mListView.getHeaderViewsCount() >0){
                        position--;
                    }
                    if (position<0 ||position>=mAdapter.getCount()){
                        return;
                    }

                    CaiPinInfo fdInfo = (CaiPinInfo) mAdapter.getItem(position);
                    Intent update_intent = new Intent(mContext,CreateDishActivity.class);
                    update_intent.putExtra("FROM",2);
                    update_intent.putExtra("DISHINFO",fdInfo);
                    startActivity(update_intent);
                }
            });

            mListView.setOnCreateContextMenuListener(this);
        }

        mListView.setOnRefreshListener(this);
        mListView.setOnLoadDataListener(this);
//        mListView.doRefresh();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        int position = info.position;
        if (mListView.getHeaderViewsCount() > 0) {
            position--;
        }
        if (position<0 || position >= mAdapter.getCount()) return;
        menu.setHeaderTitle(R.string.prompt);
        menu.add(0,0,0,R.string.delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        if (mListView.getHeaderViewsCount() > 0) {
            position--;
        }

        if (position<0 || position >= mAdapter.getCount()) return false;
        if (item.getItemId() ==0){
            CaiPinInfo cinfo = (CaiPinInfo) mAdapter.getItem(position);
            if (cinfo != null) {
                deleteOneDish(cinfo.getDishId());
            }

        }
        return super.onContextItemSelected(item);
    }

    private void deleteOneDish(String dishId){
        DishDeleteTask deleteTask = new DishDeleteTask(dishId);
        deleteTask.addListener(cityListenter);
        deleteTaskId = getEatShowApp().getTaskManager().addTask(deleteTask);

    }



    private void getCityList() {
        if(cityTaskId != -1){
            return;
        }
        if(currentPage == 0){
            mListView.setNoNextPage();
            return;
        }

        CaiPinListTask task = new CaiPinListTask(size, currentPage,businessId);
        task.addListener(cityListenter);
        cityTaskId = getEatShowApp().getTaskManager().addTask(task);
    }


    private TaskEventListener cityListenter = new ShowToastTaskEventListener(this){
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if(taskId == cityTaskId){
                cityTaskId = -1;
                if(currentPage == 1){
                    mAdapter.clearData();
                    mListView.onRefreshComplete();
                    mListView.enableLoadMore();
                }else{
                    mListView.onLoadDataComplete(true);
                }
                List<CaiPinInfo> fansList = new ArrayList<CaiPinInfo>();
                if(data != null){
                    fansList = (List<CaiPinInfo>) data;
                }

                if(fansList != null && fansList.size()>0){
                    mAdapter.updateData(fansList);
                }

                currentPage = result;


            }else if (taskId == deleteTaskId){
                deleteTaskId = -1;
                currentPage = 1;
                getCityList();
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if(taskId == cityTaskId){
                cityTaskId = -1;
                if(currentPage == 1){
                    mListView.onRefreshComplete();
                }else{
                    mListView.onLoadDataComplete(false);
                }
            }else if (taskId == deleteTaskId){
                deleteTaskId = -1;
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }

    };


   /* public void onHiddenChanged(boolean hidden) {
       onHiddenChanged(hidden);
        if(!hidden){
            //mListView.invalidate();
            if(mAdapter != null && mAdapter.getCount() == 0){
                mListView.doRefresh();
            }

        }
    }*/

    @Override
    protected void onResume() {
        super.onResume();
        mListView.doRefresh();
    }

    @Override
    public void onPullRefresh() {

    }

    @Override
    public void onLoadMore() {

        getCityList();
    }

    @Override
    public void onRefresh() {
         currentPage = 1;
        getCityList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.create_new_caipin:
                Intent intent = new Intent(mContext,CreateDishActivity.class);
                intent.putExtra("FROM",1);
                startActivity(intent);
                break;
        }
    }
}
